package com.trsj.lnsj.datasource;

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.github.pagehelper.PageHelper;

@Configuration
@MapperScan(basePackages = "com.trsj.lnsj.mapper",
    sqlSessionTemplateRef = "lnsjSqlSessionTemplate")
public class ZlnsjDataSourceConfigForMybatis {
  @Bean(name = "lnsjDataSource")
  @ConfigurationProperties(prefix = "spring.lnsj.datasource")
  @Primary
  public DataSource lnsjDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "lnsjSqlSessionFactory")
  @Primary
  public SqlSessionFactory lnsjSqlSessionFactory(
      @Qualifier("lnsjDataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    // 分页插件
    PageHelper pageHelper = new PageHelper();
    Properties props = new Properties();
    props.setProperty("reasonable", "true");
    props.setProperty("supportMethodsArguments", "true");
    props.setProperty("returnPageInfo", "check");
    props.setProperty("params", "count=countSql");
    pageHelper.setProperties(props);
    // 添加插件
    bean.setPlugins(new Interceptor[] {pageHelper});
    try {
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      bean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
      return bean.getObject();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  @Bean(name = "lnsjTransactionManager")
  @Primary
  public DataSourceTransactionManager lnsjTransactionManager(
      @Qualifier("lnsjDataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "lnsjSqlSessionTemplate")
  @Primary
  public SqlSessionTemplate lnsjSqlSessionTemplate(
      @Qualifier("lnsjSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
    return new SqlSessionTemplate(sqlSessionFactory);
  }

}
